require("module-alias/register");
require("dotenv").config();

const express = require("express");
const bodyParser = require("body-parser");
const authJwt = require("./utils/auth");
const cors = require("./utils/cors");
const response_format = require("./utils/response_format");
var createError = require("http-errors");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");

var adminRoutes = require("./routes/admin");
var v1Routes = require("./routes/v1");

var app = express();

// 设置允许跨域访问该服务.
app.use(cors);

// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");

app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));

// 对post请求的请求体进行解析
app.use(bodyParser.urlencoded({ extended: false })); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json
// 统一响应中间件
app.use(response_format);
// 配置expressjwt
app.use(authJwt);
// 注册路由
app.use("/api/admin", adminRoutes);
app.use("/api/v1", v1Routes);

// 404 处理
app.use(function (req, res, next) {
  next(createError(404));
});
// error 处理
app.use(function (err, req, res, next) {
  if (err.name === "UnauthorizedError") {
    return res.backAuthFail("Token expired or invalid");
  }
  return res.backFail(null, err.message || "");
});

module.exports = app;
